//
//  DotsView.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/5/22.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "DotsView.h"
#import "Masonry.h"
#import <POP/POP.h>
#import "SecretAlbumsConst.h"

#define DotLineWidth Adapter_X(1.0f)
#define DotWidth Adapter_X(6.0f)
#define Spacing Adapter_X(24.0f)

@interface DotsView ()

@property (nonatomic, strong) NSMutableArray *dotArray;
@property (nonatomic, assign) float beginPoint_x;
@property (nonatomic, assign) NSUInteger amount;
@property (nonatomic, assign) BOOL interactionEnabled;

@end

@implementation DotsView

- (instancetype)initWithAmount:(NSUInteger)amount
{
    if (self = [super init]) {
        self.amount = amount;
        self.interactionEnabled = YES;
        self.beginPoint_x = -Spacing * (amount-1) / 2;
        self.dotArray = [NSMutableArray array];
        for (int i=0; i<amount; i++) {
            CAShapeLayer *dotLayer = [self createDotWithIndex:i];
            [self.dotArray addObject:dotLayer];
            [self.layer addSublayer:dotLayer];
        }
    }
    
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self setDotWithPassword];
}

/** 当按钮被点击时触发，执行保存输入中密码的操作 */
- (void)operateFromCircleButton:(CircleButton *)circleButton
{
    if (!self.interactionEnabled) return;
    if (!self.password) _password = [NSMutableString new];
    
    if (CircleButtonDefault == circleButton.type) {
        if (self.password.length < self.amount) {
            [self.password appendString:circleButton.titleLabel.text];
        }
    } else if (CircleButtonCancel == circleButton.type) {
        if (self.password.length > 0) {
            [self.password deleteCharactersInRange:NSMakeRange(self.password.length-1, 1)];
        }
    }
    
    [self setDotWithPassword];
    
    if (self.password.length == self.amount
        && self.delegate
        && [self.delegate respondsToSelector:@selector(verifyPassword:FromDotsView:)]) {
        if ([self.delegate verifyPassword:self.password FromDotsView:self]) {
            self.interactionEnabled = NO;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.delegate successPassword:self.password FromDotsView:self];
                self.interactionEnabled = YES;
            });
        } else {
            [self shakeLayer];
        }
    }
}

- (void)setupPassWord:(NSString *)passWord
{
    if (!self.password) _password = [NSMutableString new];
    
    [self.password setString:passWord];
    [self setDotWithPassword];
}

- (void)cleanPassWord
{
    if (self.password) {
        [self.password deleteCharactersInRange:NSMakeRange(0, self.password.length)];
        [self setDotWithPassword];
    }
}

#pragma mark - 私有方法

/** 创建dot */
- (CAShapeLayer *)createDotWithIndex:(int)index
{
    CAShapeLayer *dotLayer = [CAShapeLayer layer];
    dotLayer.lineWidth = DotLineWidth;
    dotLayer.fillColor = [[UIColor clearColor] CGColor];
    dotLayer.strokeColor = self.tintColor.CGColor;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(self.beginPoint_x + index*Spacing, 0)
                                                        radius:DotWidth
                                                    startAngle:0
                                                      endAngle:M_PI * 2
                                                     clockwise:YES];
    dotLayer.path = path.CGPath;
    
    return dotLayer;
}

- (void)setDotWithPassword
{
    for (int i=0; i<self.dotArray.count; i++) {
        CAShapeLayer *dotLayer = self.dotArray[i];
        dotLayer.strokeColor = self.tintColor.CGColor;
        
        if (i < self.password.length) {
            dotLayer.fillColor = self.tintColor.CGColor;
        } else {
            dotLayer.fillColor = [[UIColor clearColor] CGColor];
        }
    }
}

- (void)shakeLayer
{
    self.interactionEnabled = NO;
    
    POPSpringAnimation *positionAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPositionX];
    positionAnimation.fromValue = @(self.frame.origin.x+1);
    positionAnimation.velocity = @(Adapter_X(1800));
    positionAnimation.springBounciness = 20;
    [positionAnimation setCompletionBlock:^(POPAnimation *animation, BOOL finished) {
        [self.password deleteCharactersInRange:NSMakeRange(0, self.password.length)];
        [self setDotWithPassword];
        self.interactionEnabled = YES;
    }];
    
    [self.layer pop_addAnimation:positionAnimation forKey:@"positionAnimation"];
}

@end
